﻿using DataTurnClient.Enum;
using DataTurnClient.Model;
using Newtonsoft.Json;
using Splat;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataTurnClient.Server
{
    public class HttpService 
    {
        public static Result<string> Execute(List<Job> jobList,List<RouteLine> setList, object sender)
        {
            var jobs = jobList.Where(x => x.JobCode == sender.ToString()).FirstOrDefault();
            var service = Locator.Current.GetService<LogService>();
            try
            {
                Post<String> p = new Post<String>();
                string route = jobs.JobRoute.Split(':')[1];
                if (route != "") { route = route + "/"; }
                int line = Convert.ToInt32(jobs.JobRoute.Split(':')[0]);
                RouteLine session = setList.Where(x => x.Id == line).FirstOrDefault();
                p.Post_url = $"http://{session.Ip}:{session.Port}/{session.Path}/{route}{sender.ToString()}";
                p.Post_mode = (DType.RequestType)System.Enum.Parse(typeof(DType.RequestType), jobs.JobMode);
                StringBuilder sb = new StringBuilder();
                sb.Append("{}");
                p.Post_data = sb.ToString();
                Result<string> result = p.PostSend();
                result.Data = sender.ToString() + "-" + JsonConvert.SerializeObject(result);
                jobs.JobRunStatus = Job.JobRunType.Over;
                service.WriterText("auto ", DateTime.Now.ToString("HH-mm-ss") + $"      {jobs.JobCode}" + JsonConvert.SerializeObject(result));
                return result;
            }
            catch (Exception ex)
            {
                Result<string> result = new Result<string>();
                result.Code = 500;
                result.Message = $"请求{sender.ToString()}时遇到错误：{ex.Message}";
                result.Success = false;
                jobs.JobRunStatus = Job.JobRunType.Over;
                service.WriterText("auto ", DateTime.Now.ToString("HH-mm-ss") + $"      {jobs.JobCode}" + ex.Message);
                return result;
            }
        }
    }
}
